<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>护理任务生成器</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 600px;
            width: 100%;
        }
        
        h1 {
            color: #667eea;
            text-align: center;
            margin-bottom: 10px;
            font-size: 32px;
        }
        
        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 15px;
            margin-bottom: 25px;
            border-radius: 5px;
        }
        
        .info-box h3 {
            margin: 0 0 10px 0;
            color: #667eea;
            font-size: 16px;
        }
        
        .info-box ul {
            margin: 0;
            padding-left: 20px;
            color: #555;
        }
        
        .info-box li {
            margin: 5px 0;
        }
        
        .button-group {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        button {
            flex: 1;
            padding: 15px 30px;
            font-size: 16px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: bold;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .btn-generate {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-generate:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4);
        }
        
        .btn-view {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }
        
        .btn-view:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(245, 87, 108, 0.4);
        }
        
        .btn-login {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(79, 172, 254, 0.4);
        }
        
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 10px;
            display: none;
        }
        
        .result.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
            display: block;
        }
        
        .result.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
            display: block;
        }
        
        .result.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
            display: block;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            display: none;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .stats {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }
        
        .stat-card {
            flex: 1;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🏥 护理任务生成器</h1>
        <p class="subtitle">根据护理计划、床位分配自动生成今日任务</p>
        
        <div class="info-box">
            <h3>✨ 功能说明</h3>
            <ul>
                <li>📋 根据老人的护理计划自动生成任务</li>
                <li>🎯 从床位绑定的护理员中<strong>随机分配</strong>任务</li>
                <li>📅 支持每日、每周、每月执行周期</li>
                <li>👥 护理员只能看到分配给自己的任务</li>
                <li>🔐 超级管理员可以查看所有任务</li>
            </ul>
        </div>
        
        <div class="button-group">
            <button class="btn-login" onclick="loginAndGenerate()">登录并生成任务</button>
        </div>
        
        <div class="button-group">
            <button class="btn-generate" onclick="checkData()">🔍 检查数据状态</button>
        </div>
        
        <div class="button-group">
            <button class="btn-view" onclick="viewTasks()">查看任务列表</button>
        </div>
        
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p style="margin-top: 10px; color: #667eea;">正在处理中...</p>
        </div>
        
        <div id="result" class="result"></div>
        
        <div class="stats" id="stats" style="display: none;">
            <div class="stat-card">
                <div class="stat-number" id="totalTasks">0</div>
                <div class="stat-label">生成任务数</div>
            </div>
            <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <div class="stat-number" id="elderlyCount">0</div>
                <div class="stat-label">服务老人数</div>
            </div>
        </div>
    </div>

    <script>
        let token = localStorage.getItem('token');
        
        function showResult(message, type) {
            const resultDiv = document.getElementById('result');
            resultDiv.className = `result ${type}`;
            resultDiv.innerHTML = message;
            document.getElementById('loading').style.display = 'none';
        }
        
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').style.display = 'none';
        }
        
        async function loginAndGenerate() {
            showLoading();
            
            try {
                // 1. 获取验证码
                const captchaResponse = await fetch('http://localhost:8080/captchaImage');
                if (!captchaResponse.ok) {
                    showResult('❌ 获取验证码失败', 'error');
                    return;
                }
                const captchaData = await captchaResponse.json();
                
                // 2. 登录
                const loginResponse = await fetch('http://localhost:8080/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        username: 'admin',
                        password: 'admin123',
                        code: captchaData.uuid,
                        uuid: captchaData.uuid
                    })
                });
                
                if (!loginResponse.ok) {
                    showResult('❌ 登录失败', 'error');
                    return;
                }
                
                const loginData = await loginResponse.json();
                if (!loginData.token) {
                    showResult('❌ 登录失败：' + (loginData.msg || '未知错误'), 'error');
                    return;
                }
                
                token = loginData.token;
                localStorage.setItem('token', token);
                showResult('✅ 登录成功！正在生成任务...', 'info');
                
                // 3. 等待1秒后生成任务
                setTimeout(generateTasks, 1000);
                
            } catch (error) {
                showResult('❌ 操作失败：' + error.message, 'error');
            }
        }
        
        async function generateTasks() {
            if (!token) {
                showResult('⚠️ 请先登录', 'error');
                return;
            }
            
            showLoading();
            
            try {
                const response = await fetch('http://localhost:8080/system/arrangement/generate-today-tasks', {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('生成任务响应数据:', data);
                    
                    // 从响应中提取统计信息
                    const stats = data.data || {};
                    const totalTasks = stats.totalTasks || 0;
                    const elderlyCount = stats.elderlyCount || 0;
                    
                    // 更新统计卡片
                    document.getElementById('totalTasks').textContent = totalTasks;
                    document.getElementById('elderlyCount').textContent = elderlyCount;
                    document.getElementById('stats').style.display = 'flex';
                    
                    if (totalTasks > 0) {
                        showResult(`✅ 任务生成成功！<br><br>📊 统计信息：<br>• 生成任务数：${totalTasks} 条<br>• 服务老人数：${elderlyCount} 位<br><br>📝 任务已根据以下规则生成：<br>• 护理计划中的护理项目<br>• 执行周期（每日/每周/每月）<br>• 从床位绑定的护理员中随机分配`, 'success');
                    } else {
                        showResult(`⚠️ 今日无需生成新任务<br><br>可能原因：<br>• 今日不在护理项目的执行周期内<br>• 所有老人的护理计划今日无任务`, 'info');
                    }
                } else {
                    const errorText = await response.text();
                    showResult(`❌ 生成任务失败：${response.status} - ${errorText}`, 'error');
                }
            } catch (error) {
                showResult(`❌ 连接失败：${error.message}`, 'error');
            }
        }
        
        async function checkData() {
            if (!token) {
                showResult('⚠️ 请先点击"登录并生成任务"按钮登录！', 'error');
                return;
            }
            
            showLoading();
            
            try {
                const response = await fetch('http://localhost:8080/system/arrangement/debug-task-generation', {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/json'
                    }
                });
                
                console.log('调试接口响应状态:', response.status);
                
                if (response.status === 401) {
                    showResult('❌ 权限验证失败！请先点击"登录并生成任务"按钮重新登录。', 'error');
                    return;
                }
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('调试接口响应数据:', data);
                    const debugData = data.data || data;
                    
                    let resultHtml = '<h3>📊 数据状态检查结果：</h3>';
                    resultHtml += `<p><strong>在住老人数量：</strong>${debugData.elderlyWithPlansCount || 0}</p>`;
                    
                    if (debugData.detailList && debugData.detailList.length > 0) {
                        resultHtml += '<div style="max-height: 300px; overflow-y: auto; text-align: left; margin-top: 10px;">';
                        debugData.detailList.forEach((detail, index) => {
                            const elderly = detail.elderlyInfo;
                            resultHtml += `<div style="border: 1px solid #ddd; padding: 10px; margin: 5px 0; border-radius: 5px;">`;
                            resultHtml += `<strong>老人${index + 1}：</strong>${elderly.elderly_name || '未知'}<br>`;
                            resultHtml += `床位：${elderly.bed_id || '无'}<br>`;
                            resultHtml += `护理计划：${elderly.plan_name || '无'}<br>`;
                            resultHtml += `护理员数量：${detail.caregiverCount || 0}个<br>`;
                            resultHtml += `护理项目数量：${detail.nursingItemsCount || 0}个`;
                            resultHtml += `</div>`;
                        });
                        resultHtml += '</div>';
                    } else {
                        resultHtml += '<p style="color: red;">❌ 没有找到在住老人或护理计划数据！</p>';
                        resultHtml += '<p>请确保：</p>';
                        resultHtml += '<ul style="text-align: left;">';
                        resultHtml += '<li>老人已入住且分配了床位</li>';
                        resultHtml += '<li>老人关联了护理等级</li>';
                        resultHtml += '<li>护理等级绑定了护理计划</li>';
                        resultHtml += '<li>护理计划中有护理项目绑定</li>';
                        resultHtml += '<li>床位分配了护理员</li>';
                        resultHtml += '</ul>';
                    }
                    
                    showResult(resultHtml, 'info');
                } else {
                    const errorText = await response.text();
                    console.error('调试接口错误响应:', errorText);
                    showResult(`❌ 检查失败（状态码${response.status}）<br>请先点击"登录并生成任务"按钮确保已登录。`, 'error');
                }
            } catch (error) {
                console.error('调试接口异常:', error);
                showResult(`❌ 连接失败：${error.message}<br>请确保后端服务已启动。`, 'error');
            }
        }
        
        function viewTasks() {
            window.location.href = 'http://localhost:80/#/system/arrangement';
        }
        
        // 页面加载时检查是否已登录
        window.onload = function() {
            if (token) {
                showResult('✅ 检测到已登录状态，可以直接生成任务或检查数据', 'info');
            }
        };
    </script>
</body>
</html>

